import sha1 from 'sha1'
import getRawBody from 'raw-body'
import * as util from './util'

export default (opts, reply) => async (ctx, next) => {
  const {
    signature,
    nonce,
    timestamp,
    echostr
  } = ctx.query
  let str = [opts.token, timestamp, nonce].sort().join('')
  const strsha = sha1(str)

  if (ctx.method === 'GET') {
    strsha !== signature ? ctx.body = 'Failed' : ctx.body = echostr
  } else if (ctx.method === 'POST') {
    if (strsha !== signature) {
      ctx.body = 'Failed'
      return
    }
    const reqXML = await getRawBody(ctx.req, {
      length: ctx.length,
      limit: '1mb',
      encoding: ctx.charset
    })

    const ctn = await util.parseXML(reqXML).catch(err => {
      console.error(err)
    })
    let msg = util.format(ctn.xml)
    ctx.weixin = msg

    await reply.apply(ctx, [ctx, next])
    const replyBody = ctx.body
    msg = ctx.weixin
    const wxTmpl = util.toWXtmpl(replyBody, msg)
    ctx.status = 200
    ctx.type = 'application/xml'
    ctx.body = wxTmpl
  }
}
